import logging
import pickle

import webapp2
from google.appengine.ext import db
from google.appengine.api import users
from . import Item, Collection, User

class Log(db.Model):
	"""Represents entries in the audit log for administrative
	purposes"""
	datetime = db.DateTimeProperty(required=True, auto_now_add=True)
	performer = db.UserProperty(auto_current_user_add=True)
	changed_item = db.ReferenceProperty(Item.Item)
	changed_user = db.UserProperty()
	changed_collection = db.ReferenceProperty(Collection.Collection)

	level = db.IntegerProperty(
		required=True,
		default=logging.INFO,
		choices=set([
			logging.DEBUG,
			logging.INFO,
			logging.WARNING,
			logging.ERROR,
			logging.CRITICAL
		])
	)

	message = db.TextProperty()

	@webapp2.cached_property
	def changed_obj(self):
		if self.changed_item:
			return "Item: " + self.changed_item.title
		elif self.changed_user:
			return "User: " + User.User.getUser(self.changed_user).getName()
		elif self.changed_collection:
			return self.changed_collection
		else:
			return "No target"

class LogHandler(logging.Handler):
	def emit(self, record):
		entry = Log(level=record.levelno, message=record.message)
		if entry.__dict__.get('performer', False):
			entry.performer = record.performer

		try:
			if isinstance(record.target, Item.Item):
				entry.changed_item = record.target
			elif isinstance(record.target, users.User):
				entry.changed_user = record.target
			elif isinstance(record.target, Collection.Collection):
				entry.changed_collection = record.target
			else:
				raise ValueError('Invalid target type.')
		except AttributeError:
			pass

		entry.put()
